package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.StatusStartOrStopExecption;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 新增套餐
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result save(SetmealDTO dto) {
        //1.插入套餐信息
        Setmeal setmeal = new Setmeal();

        // 1.1拷贝数据
        BeanUtils.copyProperties(dto,setmeal);

        // 1.2补全数据
        setmeal.setStatus(StatusConstant.DISABLE);

        // 1.3插入套餐信息
        setmealMapper.insert(setmeal);

        //2.插入套餐包含的菜品
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();
        for (SetmealDish dish : setmealDishes) {
            dish.setSetmealId(setmeal.getId());
        }

        // 2.1插入菜品信息
        setmealDishMapper.insert(setmealDishes);

        //清除套餐缓存
        String KEY  = "setmeal:"+dto.getCategoryId();
        redisTemplate.delete(KEY);
        return Result.success();
    }

    /**
     * 条件分页查询
     * @return
     */
    @Override
    public Result queryByPage(SetmealPageQueryDTO dto) {
        // 开启分页，设置参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<SetmealVO> setmealVOS = setmealMapper.selectByPage(dto);

        //封装参数
        PageResult pageResult = new PageResult();
        pageResult.setTotal(setmealVOS.getTotal());
        pageResult.setRecords(setmealVOS);
        return Result.success(pageResult);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result deleteByIds(List<Long> ids) {
        //1.起售中的套餐不能删除
        int count =  setmealMapper.queryStatusByIds(ids);
        if (count>0){
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }
        //清除套餐缓存
        //获取套餐分类
        for (Long id : ids) {
            Setmeal setmeal = setmealMapper.selectById(id);
            Long categoryId = setmeal.getCategoryId();
            String KEY  = "setmeal:"+setmeal.getCategoryId();
            redisTemplate.delete(KEY);
        }
        //2. 删除套餐
        setmealMapper.deleteByIds(ids);
        //3. 删除套餐对应的口味表
        setmealDishMapper.deleteBySetmealIds(ids);
        return Result.success();
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public Result selectById(Long id) {
        //查询套餐信息
        Setmeal setmeal = setmealMapper.selectById(id);
        //查询套餐包含菜品信息
        List<SetmealDish> setmealDishes = setmealDishMapper.selectBySetmealId(id);
        //封装返回数据
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal,setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);
        return Result.success(setmealVO);
    }


    /**
     * 修改套餐
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result update(SetmealDTO dto) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(dto,setmeal);
        //补全数据 AOP

        //1.修改套餐信息
        setmealMapper.update(setmeal);
        //2.修改套餐包含的菜品
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(dto.getId());
        }
        if ( setmealDishes!=null && setmealDishes.size()!=0) {
            // 先删除所有菜品
            List<Long> longs  = new ArrayList<>();
            longs.add(dto.getId());
            setmealDishMapper.deleteBySetmealIds(longs);
            // 再添加套餐包含菜品信息
            setmealDishMapper.insert(setmealDishes);
        }

        //删除缓存
        String KEY = "setmeal:"+setmeal.getCategoryId();
        redisTemplate.delete(KEY);
        return Result.success();
    }

    /**
     * 起售停售
     * @return
     */
    @Override
    public Result startOrStop(Integer status, Long id) {
        //套餐中有未起售的菜品不能起售
        if (status==1){
            int c = dishMapper.selectCountBySetmealId(id);
            if (c>0){
                    throw new StatusStartOrStopExecption(MessageConstant.SETMEAL_ENABLE_FAILED);
            }
        }
        Setmeal Setmeal1 = Setmeal.builder()
                .id(id)
                .status(status).build();

        setmealMapper.update(Setmeal1);

        //删除缓存
        Setmeal setmeal = setmealMapper.selectById(id);
        String KEY = "setmeal:"+setmeal.getCategoryId();
        redisTemplate.delete(KEY);
        return Result.success();
    }

    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        String KEY = "setmeal:"+setmeal.getCategoryId();
        //先从缓存查
        ListOperations<String, String> listOperations = redisTemplate.opsForList();
        List<String> range = listOperations.range(KEY, 0, -1);
        System.out.println(range);
        if (CollectionUtils.isNotEmpty(range)){
            List<Setmeal> collect = range.stream().map(x -> JSON.parseObject(x, Setmeal.class)
            ).collect(Collectors.toList());
            return collect;
        }

        //没有就去数据库查
        List<Setmeal> list = setmealMapper.list(setmeal);

        //不为空就添加进缓存
        if (CollectionUtils.isNotEmpty(list)){
            List<String> collect = list.stream().map(x -> JSON.toJSONString(x)).collect(Collectors.toList());
            listOperations.leftPushAll(KEY,collect);
            System.out.println(collect);
        }

        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }

}
